package teamgodeater.hicarnet;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;

import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import teamgodeater.hicarnet.Data.WeatherData;
import teamgodeater.hicarnet.RestClient.RestClient;

/**
 * Created by G on 2016/7/21 0021.
 */

public class WeatherHelp {

    private static final String KEY = "195046990e59df486a5c87266e17a84e";
    private static final String URL = "http://v.juhe.cn/weather/index";
    private static WeatherData weatherData;
    private static boolean succeed = false;
    private static Context context;
    private static String city;

    public static void notifyWeather() {
        if (weatherData == null || weatherData.getError_code() != 0) {
            errorr(-2);
            return;
        }
        Notification.Builder builder = new Notification.Builder(context);
        builder.setSmallIcon(R.drawable.logo_outline);
        WeatherData.ResultBean.TodayBean today = weatherData.getResult().getToday();
        String title = "愿明天是个晴天~~";
        if (today.getWeather().contains("晴"))
            title = "愿你有个好心情~~";
        builder.setContentTitle(title);
        builder.setContentText(city + " " + today.getWeather() + " , " + today.getTemperature());
        builder.setAutoCancel(true);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(23,builder.build());
        succeed = true;
    }

    public static void getWeather() {
        String cityName = city.substring(0, city.length() - 1);

        final RestClient restClient = new RestClient();
        try {
            restClient.addUrlParams("cityname", URLEncoder.encode(cityName, "utf-8")).addUrlParams("key", KEY);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        restClient.loginOperation(C.GET, URL, restClient, new RestClient.OnResultListener<String>() {
            @Override
            public void succeed(String bean) {
                if (bean == null || bean.equals("")) {
                    errorr(-1);
                    return;
                }
                Gson gson = new Gson();
                weatherData = gson.fromJson(bean, WeatherData.class);
                if (weatherData == null) {
                    errorr(-2);
                    return;
                }
                notifyWeather();
            }

            @Override
            public void error(int code) {
                errorr(code);
            }
        });

    }

    public static void weatherNotify(String city, Context context) {
        if (succeed || city == null || city.equals(""))
            return;
        WeatherHelp.city = city;
        WeatherHelp.context = context;
        getWeather();
    }

    private static void errorr(int i) {
    }
}
